package com.meida.module.bus.provider.controller;

import cn.hutool.log.StaticLog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.springmvc.base.BaseController;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.FlymeUtils;
import com.meida.common.utils.RedisUtils;
import com.meida.common.utils.StringUtils;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.provider.api.service.SyncSrmService;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsOaUtil;
import com.meida.module.bus.provider.service.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;


/**
 * 100材料计划表控制器
 *
 * @author flyme
 * @date 2020-10-09
 */
@RestController
@RequestMapping("/system/bmp/")
public class BusMaterialPlan100Controller extends BaseController<BusMaterialPlan100Service, BusMaterialPlan100> {
    @Autowired
    private BusMaterialPlan200Service plan200Service;
    @Autowired
    private BusVersionService busVersionService;
    @Autowired
    private PmsOaUtil pmaOaUtil;
    @Autowired
    private BusMaterialSrmSubService busMaterialSrmSubService;
    @Autowired
    private SyncSrmService syncSrmService;
    @Autowired
    private BmmdMaterialService bmmdMaterialService;
    @Autowired
    private BbpUnitService bbpUnitService;
    @Autowired
    private BusProjectFileService busProjectFileService;

    @Autowired
    RedisUtils redisUtils;

    @ApiOperation(value = "100材料计划表-分页列表", notes = "100材料计划表分页列表")
    @GetMapping(value = "page")
    public ResultBody pageList(@RequestParam(required = false) Map params) {
//        return bizService.pageList(params);
        ResultBody rs = null;
        if (FlymeUtils.isNotEmpty(params.get("version"))) {
            String version = params.get("version").toString();
            String s = StringUtils.substringBefore(version, ".");
            //如果大版本是100的话就调用本类的service，否则版本是200调用200的service
            if (s.equals("100")) {
                rs = bizService.pageList(params);
            } else {
                rs = plan200Service.pageList(params);
            }
        } else {
            rs = bizService.pageList(params);
        }
        if(null != rs.getData()) {
            Page<EntityMap> page = (Page<EntityMap>) rs.getData();
            List<EntityMap> datMapList = page.getRecords();
            datMapList.stream().forEach(dataMap->{
                Map<String, Object> searchMap = Maps.newHashMap();
                searchMap.put("materialCode", dataMap.get("materialCode"));
                Collection<BmmdMaterial> bmmdMaterials = bmmdMaterialService.listByMap(searchMap);

                searchMap = Maps.newHashMap();
                if(!CollectionUtils.isEmpty(bmmdMaterials)) {
                    searchMap.put("unitCode", bmmdMaterials.stream().findFirst().get().getBaseUnitCode());
                    Collection<BbpUnit> bbpUnitList = bbpUnitService.listByMap(searchMap);
                    dataMap.put("materialDescSrm", bbpUnitList.stream().findFirst().get().getUnitName());
                }
            });
            page.setRecords(datMapList);
            rs.data(page);
        }
        return rs;
    }

    @ApiOperation(value = "材料修改变更", notes = "材料修改变更")
    @PostMapping(value = "copyAndUpdate")
    public ResultBody copyAndUpdate(@RequestParam(required = false) Map params) {
        ResultBody rsb = bizService.copyAndUpdateplan(params);
        Long projectId = TypeUtils.castToLong(params.get("projectId"));
//        pmaOaUtil.updateMaterialBase(projectId, ApiConstants.VER_100, ApiConstants.INT_ZERO);
        return rsb;
    }


    @ApiOperation(value = "订单下达修改采购量", notes = "订单下达修改采购量")
    @PostMapping(value = "upSrmPurseCount")
    public ResultBody upSrmPurseCount(String dataArray) {
        if (FlymeUtils.isNotEmpty(dataArray)) {
            List<BusMaterialSrmSub> srmSubs = JSON.parseArray(dataArray, BusMaterialSrmSub.class);
            List<BusMaterialSrmSub> srmList = new ArrayList();
            for (BusMaterialSrmSub sub : srmSubs) {
                BusMaterialSrmSub newsub = busMaterialSrmSubService.getById(sub.getBusMaterialSrmSubId());
                StaticLog.info("更新前---newsub--：" + newsub.toString());
                if (FlymeUtils.isNotEmpty(sub.getOrderThisTimeQty())) {
                    if (sub.getOrderThisTimeQty().compareTo(newsub.getOrderSurplusQty()) > 0) {
                        return ResultBody.failed("本次采购量不能大于剩余采购量");
                    }
                    // 已下数量
                    // newsub.setOrderOutQty(NumberUtil.add(newsub.getOrderOutQty(), sub.getOrderThisTimeQty()));
                    // 剩余数量
                    // newsub.setOrderSurplusQty(newsub.getOrderSurplusQty().subtract(sub.getOrderThisTimeQty()));
                    // 本次下单数量
                    newsub.setOrderThisTimeQty(sub.getOrderThisTimeQty());
                    newsub.setSycnFlgForOpen(ApiConstants.ORDER_OPEN_FLG_SYNC_ING);
                    srmList.add(newsub);
                } else {
                    return ResultBody.failed("本次采购量不能为空");
                }
            }
            if (srmList.size() > 0) {
                srmList.stream().forEach(srmObj-> System.out.println(srmObj.toString()));
                boolean bussub = busMaterialSrmSubService.updateBatchById(srmList);
                //订单下达接口
//                int a = syncSrmService.openOrderRequest(srmList);
////                if (a != 0) {
////                    return ResultBody.failed("订单下达失败");
////                }
            }
        }
        return ResultBody.ok();
    }


    @ApiOperation(value = "100材料-导出模板", notes = "100材料-导出模板")
    @PostMapping(value = "export100planTemplate")
    public void export100planTemplate(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) Map params) {
        bizService.export(params, request, response, "100材料计划", "100材料计划", "busmaterialPlan100ExportHandler");
    }


    @ApiOperation(value = "材料申请批量导出", notes = "材料申请批量导出")
    @PostMapping(value = "exportUrl")
    public void exportUrl(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) Map params) {
        if (FlymeUtils.isNotEmpty(params.get("version"))) {
            String version = params.get("version").toString();
            String s = StringUtils.substringBefore(version, ".");
            //如果大版本是100的话就调用本类的service，否则版本是200调用200的service
            if (s.equals("100")) {
                bizService.export(params, request, response, "100材料申请", "100材料申请", "busPurchases100ExportHandler");
            } else {
                plan200Service.export(params, request, response, "200材料申请", "200材料申请", "busPurchases200ExportHandler");
            }
        }
    }

    @ApiOperation(value = "100材料-导入数据", notes = "100材料-导入数据")
    @PostMapping(value = "import100UpdateData")
    public ResultBody import100UpdateData(@RequestParam(required = false) Map params, @RequestParam("file") MultipartFile file) {
        ResultBody resultBody = bizService.importOnUpdateplan100Data(file, params);
        Long projectId = TypeUtils.castToLong(params.get("projectId"));
//        pmaOaUtil.updateMaterialBase(projectId, ApiConstants.VER_100, ApiConstants.INT_ZERO);
        return resultBody;
    }

    @ApiOperation(value = "100材料申请-导入数据", notes = "100材料申请-导入数据")
    @PostMapping(value = "importPurseDetail")
    public ResultBody import100PurseDetail(@RequestParam(required = false) Map params, @RequestParam("file") MultipartFile file) {
        if (FlymeUtils.isNotEmpty(params.get("version"))) {
            String version = params.get("version").toString();
            String s = StringUtils.substringBefore(version, ".");
            //如果大版本是100的话就调用本类的service，否则版本是200调用200的service
            if (s.equals("100")) {
                return bizService.import100PurseDetail(file, params);
            } else {
                return plan200Service.import200PurseDetail(file, params);
            }
        }
        return ResultBody.ok();
    }

    @ApiOperation(value = "获取缓存导入数据", notes = "获取缓存导入数据")
    @PostMapping(value = "getexcelPurseDetail")
    public ResultBody getexcelPurseDetail(@RequestParam(required = false) String excelKey) {
        if (FlymeUtils.isNotEmpty(excelKey)) {
            return ResultBody.ok(redisUtils.getList(excelKey));
        }
        return ResultBody.ok();
    }

    @ApiOperation(value = "合并100数据", notes = "合并100数据")
    @PostMapping(value = "margeplan100")
    public ResultBody margeplan100(@RequestParam(required = false) Map params) {
        return bizService.mergeplan100(params);
    }

    @ApiOperation(value = "100材料计划表-分页列表", notes = "100材料计划表分页列表")
    @GetMapping(value = "pagedetail")
    public ResultBody pagedetail(@RequestParam(required = false) Map params) {
        return bizService.pageList(params);
    }


    @ApiOperation(value = "转存200-分页列表", notes = "转存200")
    @PostMapping(value = "zcdetatil")
    public ResultBody zcdetatil(@RequestParam(required = false) Long[] materialPlanIds, Long projectId) {
        return bizService.transferedVersion(materialPlanIds, projectId);
    }

    @ApiOperation(value = "当前版本是否可操作修改变更", notes = "当前版本是否可操作修改变更")
    @PostMapping(value = "isOpentorVersStatus")
    public ResultBody isOpentorVersStatus(String versionType, Long projectId) {
        EntityMap map = new EntityMap();
        boolean buttonStatus = bizService.isOpentorVersStatus(projectId, versionType);
        if (buttonStatus) {
            map.put("buttonStatus", 1);
        } else {
            map.put("buttonStatus", 0);
        }
        return ResultBody.ok(map);
    }

    @ApiOperation(value = "材料申请", notes = "材料申请")
    @PostMapping(value = "applyPurchase")
    public ResultBody applyPurchase(String dataArray, Long projectId, String versionId, String excelKey,@RequestParam(required = false) String uniqueFlag) throws Exception {
        if (FlymeUtils.isNotEmpty(excelKey)) {
            redisUtils.del(excelKey);//清空redis中导入的数据
        }
        if (FlymeUtils.isNotEmpty(dataArray)) {

            List<EntityMap> listentityMap = JSON.parseArray(dataArray, EntityMap.class);

//            if(FlymeUtils.isEmpty(entityMap.get("purchaseCount"))){
//                return ResultBody.failed("参数不完整,缺少采购数量");
//            }
//            if(FlymeUtils.isEmpty(entityMap.get("vendorId"))){
//                return ResultBody.failed("参数不完整,请选择供应商");
//            }
//            if(FlymeUtils.isEmpty(entityMap.get("caseType"))){
//                return ResultBody.failed("参数不完整,请选择单据类型");
//            }
//            if(FlymeUtils.isEmpty(entityMap.get("receivedDate"))){
//                return ResultBody.failed("参数不完整,请选择到货日期");
//            }
//            Long versionId=Long.parseLong(params.get("versionId").toString());
//            Long projectId=Long.parseLong(params.get("projectId").toString());
            long pusId = IdWorker.getId();
            BusPurchase busPurchase = new BusPurchase();
            busPurchase.setProjectId(projectId);
            busPurchase.setState(0);
            busPurchase.setUserId(OpenHelper.getUserId());
            busPurchase.setPurchaseId(IdWorker.getId());
            busPurchase.setPurchaseNo(DateUtils.getCurrentTimestampStr());
            List<BusPurchaseDetails> lists = new ArrayList<>();
            Long[] materialPlanIds = {};
            List<Long> strArray = new ArrayList<>();
            for (EntityMap emap : listentityMap) {
                BusPurchaseDetails details = new BusPurchaseDetails();
                details.setUserId(OpenHelper.getUserId());
                details.setState(0);
                details.setPurchaseId(busPurchase.getPurchaseId());
                details.setVendorName(emap.get("vendorName"));
                details.setReceivedDate(emap.get("receivedDate").toString());
                details.setDocumentType(emap.get("caseType"));
                details.setPurchaseNum(TypeUtils.castToBigDecimal(emap.get("purchaseCount")));
                details.setMaterialId(Long.parseLong(emap.get("materialPlanId")));
                details.setProjectId(projectId);
                details.setOrderflg("0");

                // 材料WBS代码
                details.setMaterialWbsCode(emap.get("materialWbsCode"));
                // 物料代码
                details.setMaterialCode(emap.get("materialCode"));
                // 品牌
                details.setBrandName(emap.get("brandName"));
                // 技术参数
                details.setTechnicalData(emap.get("technicalData"));
                // 备注
                details.setRemark(emap.get("remark"));
                lists.add(details);
            }
            busPurchase.setDetails(lists);
//            BusVersion versionEntity = busVersionService.getById(versionId);
            String versionStr = versionId.substring(0, 3);
            //更新申请记录到上传的附件记录中
            if(StringUtils.isNotBlank(uniqueFlag)) {
                busProjectFileService.updatePurchaseId(uniqueFlag, busPurchase.getPurchaseId());
            }
            //如果大版本是100的话就调用本类的service，否则版本是200调用200的service
            if (versionStr.equals("100")) {
                return bizService.updateMaterial(projectId, Long.parseLong(versionStr), busPurchase);
            } else {
                return plan200Service.updateMaterial(projectId, Long.parseLong(versionStr), busPurchase);
            }
        }
        return ResultBody.ok("操作成功");
    }

    @ApiOperation(value = "开口订单查询", notes = "开口订单查询")
    @GetMapping(value = "selectInnerOrder")
    public ResultBody selectInnerOrder(@RequestParam(required = false) Map params) {

        if (FlymeUtils.isEmpty(params.get("materialPlanId"))) {
            return ResultBody.failed("参数为空");
        }
        String ver = "100";
        if(params.containsKey("ver") && params.get("ver")!=null) {
            ver = params.get("ver").toString();
        }
        if(ver.startsWith("100")) {
            List<EntityMap> entityMaps = bizService.selectInnerOrder(null, Long.parseLong(params.get("materialPlanId").toString()));
            return ResultBody.ok(entityMaps);
        }
        List<EntityMap> entityMaps = plan200Service.selectInnerOrder(null, Long.parseLong(params.get("materialPlanId").toString()));
        return ResultBody.ok(entityMaps);

    }

    @ApiOperation(value = "100材料计划表-列表", notes = "100材料计划表列表")
    @GetMapping(value = "list")
    public ResultBody list(@RequestParam(required = false) Map params) {
        return bizService.listEntityMap(params);
    }

    @ApiOperation(value = "100材料计划表-添加", notes = "添加100材料计划表")
    @PostMapping(value = "save")
    public ResultBody save(@RequestParam(required = false) Map params) {
        return bizService.add(params);

    }
    @ApiOperation(value = "100材料计划表-更新", notes = "更新100材料计划表")
    @PostMapping(value = "update")
    public ResultBody update(@RequestParam(required = false) Map params) {
        return bizService.edit(params);
    }

    @ApiOperation(value = "100材料计划表-删除", notes = "删除100材料计划表")
    @PostMapping(value = "remove")
    public ResultBody remove(@RequestParam(required = false) Map params) {
        return bizService.delete(params);
    }


    @ApiOperation(value = "100材料-导入数据", notes = "100材料-导入数据")
    @PostMapping(value = "import100planData")
    public ResultBody import100planData(@RequestParam(required = false) Map params, @RequestParam("file") MultipartFile file, Long projectId) {
        ResultBody resultBody = bizService.importOnUpdateplan100Data(file, params);
        return resultBody;
    }


    @ApiOperation(value = "100材料计划表-详情", notes = "100材料计划表详情")
    @GetMapping(value = "get")
    public ResultBody get(@RequestParam(required = false) Map params) {
        return bizService.get(params);
    }


    @ApiOperation(value = "获取历史版本", notes = "获取历史版本")
    @GetMapping(value = "selectVersionList")
    public ResultBody selectVersionList(@RequestParam(required = false) Map params) {
        List<EntityMap> entityMapList = bizService.selectVersionList(params);
        return ResultBody.ok().data(entityMapList);
    }

    @ApiOperation(value = "判断材料行是否存在变更中待审核的数据", notes = "判断材料行是否存在变更中待审核的数据")
    @GetMapping(value = "checkUnderReview")
    public ResultBody checkHasUnderReviewRecord(@RequestParam Long materialPlanId) {
        CriteriaUpdate<BusMaterialPlan100> cu = new CriteriaUpdate();
        cu.eq("parentId", materialPlanId);
        cu.eq("applayStatus", 1);//审批中
        int count = bizService.count(cu);
        if(count > 0) {
            return ResultBody.ok().data("Y");
        }
        return ResultBody.ok().data("N");
    }

}
